#!/usr/bin/env ruby
#
#  Created by sjavey on 2007-07-10.
#  Copyright (c) 2007. All rights reserved.

#
# To run this program you must add /full-path.../note19/trunk to your RUBYLIB
# environment variable.
#

require 'n19gpx/document'

class GoogleMapGpx
  
  def initialize(gpxfile)
    @gpx = N19GPX::Document.new(gpxfile)
    @index = -1
    @counter = -1
  end
    
  def googleKey
    return "ABQIAAAAUnY6UsCW7it4ynNVu1Y5yBSxX2zfTXvgNqo-1Sb4KGdzxJeSsxSMxoquhxxH3JhZzsr1mB3ZxpioMA"
  end
    
  def boundsHtml
    str = <<EOS

    var sw = new GLatLng(#{@gpx.bounds.minlat}, #{@gpx.bounds.minlon});
    var ne = new GLatLng(#{@gpx.bounds.maxlat}, #{@gpx.bounds.maxlon})
    var bounds = new GLatLngBounds(sw, ne);
    var boundsOverlay = null;
    var isBoundsOverlayVisible = true;
    
    function setBoundsOverlay() {
      var box= [];
      box.push(new GLatLng(#{@gpx.bounds.maxlat},#{@gpx.bounds.minlon}));
      box.push(new GLatLng(#{@gpx.bounds.maxlat},#{@gpx.bounds.maxlon}));
      box.push(new GLatLng(#{@gpx.bounds.minlat},#{@gpx.bounds.maxlon}));
      box.push(new GLatLng(#{@gpx.bounds.minlat},#{@gpx.bounds.minlon}));
      box.push(new GLatLng(#{@gpx.bounds.maxlat},#{@gpx.bounds.minlon}));
      boundsOverlay = new GPolyline(box, "#FF00FF");
    }
EOS
  end
    
  def addPoint(point) 
    str = ""
    if (@counter > 100 or @counter == -1)
      @counter = 0
      @index = @index +1
      str = "\n\ttracks[#{@index}] = [];\n"
      str << "\ttrackVisible[#{@index}] = true;\n"
      str << "\ttrackOverlay[#{@index}] = null;\n"
    end
    @counter = @counter + 1
    str << "\ttracks[#{@index}].push(new GLatLng(#{point.lat},#{point.lon}));\n"
  end
  
  def trackHtml(track)
    str = ""
    track.points.each { |point|
      str << addPoint(point)
    }
     return str;
  end

  def html
    @htmlHeader = <<EOS
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>note19 Scripts</title>
    <script 
      src="http://maps.google.com/maps?file=api&v=2&key=#{googleKey()}" 
      type="text/javascript">
    </script>
    <script type="text/javascript">
    //<![CDATA[

    var map = null;
    #{boundsHtml()}

    // setup track points 
    var tracks = [];
    var trackVisible = [];
    var trackOverlay = [];


    function setupTracks() {
      #{tracksHtml()}      
    }
    
    #{mapControlFunctions()} 

    function showHideTracksOverlay() {
      for (var i in tracks) {
        if (trackVisible[i]) {
          map.addOverlay(trackOverlay[i]);           
        } else {
          map.removeOverlay(trackOverlay[i]);
        }
      }
    }
    
    function setTracksOverlay() {
      for (var i in tracks) {
        trackOverlay[i] = new GPolyline(tracks[i]);           
      }
    }
    
    var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapsfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);
    
    function load() {
      if (GBrowserIsCompatible()) {
        var ct = new GLatLng(37.4419, -122.1419);
        map = new GMap2(document.getElementById("map"));
        map.setCenter(bounds.getCenter(), 12);

        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GOverviewMapControl());
        setupTracks();
        setTracksOverlay();
        setBoundsOverlay();
        //map.addOverlay(boundsOverlay);
        //map.addOverlay(new GMarker(bounds.getCenter()));
        showHideTracksOverlay();
        var min_ele = new GLatLng(#{@gpx.min_point.lat}, #{@gpx.min_point.lon});
        var max_ele = new GLatLng(#{@gpx.max_point.lat}, #{@gpx.max_point.lon});
 		    var min_icon = new GIcon(baseIcon);
 		    min_icon.image = "http://javey.net/images/icons/icong1.png";
 		    var min_marker = new GMarker(min_ele, {icon: min_icon, draggable: true});
 		    var min_content = "<div style='background-color:white'><font color='black'><br/>Minimum elevation #{@gpx.min_point.ele} meters</font><br/></div>";
 		    GEvent.addListener(min_marker, "click",  function() {min_marker.openInfoWindowHtml(min_content);});
 		    map.addOverlay(min_marker);

 		    var max_icon = new GIcon(baseIcon);
 		    max_icon.image = "http://javey.net/images/icons/iconr1.png";
 		    var max_marker = new GMarker(max_ele, {icon: max_icon, draggable: true});
 		    var max_content = "<div style='background-color:white'><font color='black'><br/>Maximum elevation #{@gpx.max_point.ele} meters</font><br/></div>";
 		    GEvent.addListener(max_marker, "click",  function() {max_marker.openInfoWindowHtml(max_content);});
 		    map.addOverlay(max_marker);
            
      }
    }
    
    //]]>
    </script>
  </head>
  <body onload="load()" onunload="GUnload()">
    <div id="map" style="width: 800px; height: 500px"></div>
  </body>
</html>
EOS
  end
  
  def tracksHtml
    str = ""
    @gpx.tracks.each {|track|
     str << trackHtml(track)
    }
    return str
  end
  
  def mapControl
    str = <<EOS
    
    <form>

      <input type="button" value="Hide Bounds" onclick="showHideBoundsOverlay(this)"/>
      #{mapTrackControl()}
      <input type="button" value="Larger Size Map" onclick="maximize()"/>
      <input type="button" value="Smaller Size Map" onclick="minimize()"/>
    </form>
EOS
  end

  def mapTrackControl
    str = "\n"
    @gpx.tracks.each {|track|
      ts = <<EOS
      <input type="button" value="Hide Track #{track.number} [#{track.points.size} points]" onclick="showHideTrack(#{track.number}, this)" />
EOS
    str << ts
    }
    return str
  end
  
  def mapControlFunctions
    str = <<EOS
    
    function showHideBoundsOverlay(button) {
      if (isBoundsOverlayVisible) {
        map.removeOverlay(boundsOverlay);
      } else {
        map.addOverlay(boundsOverlay);
      }
      isBoundsOverlayVisible = !isBoundsOverlayVisible;
      button.value = isBoundsOverlayVisible ? "Hide Bounds" : "Show Bounds"
    }
    
    function showHideTrack(i, button) {
      trackVisible[i] = !trackVisible[i];
      showHideTracksOverlay();
      button.value = trackVisible[i] ? "Hide Track " + i : "Show Track " + i;
      button.value += " [" + tracks[i].length + " points]";
      document.getElementById("textId").value = "Element " + i;
    }
    
    function maximize() {
        var mapdiv = document.getElementById("map");
        mapdiv.style.width="1000px";
        mapdiv.style.height="550px";
    }

    function minimize() {
        var mapdiv = document.getElementById("map");
        mapdiv.style.width="680px";
        mapdiv.style.height="400px";
    }  
EOS
  end
end

# test the googlemap generation

track = "21-oct-2007"
gmap = GoogleMapGpx.new(track + ".gpx")
file = File.new(track + ".html", "w")
file.puts gmap.html()
file.close
